<template>
  <base-breadcrumb :title="title">
    <!-- 确认签名 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <a-card :bordered="false">
          <title-name title="处理"></title-name>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                label="签字图片"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
                prop="imgBase64"
              >
                <a-upload
                  name="file"
                  accept="image/*"
                  list-type="picture-card"
                  :file-list="fileList"
                  :disabled="editModel == 0 || resolveInfo"
                  :before-upload="beforeUpload"
                  @change="handleImageChange"
                  @preview="handlePreview"
                >
                  <div v-if="fileList.length < 1">
                    <a-icon type="plus" />
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="处理信息"
                prop="handleDetails"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
              >
                <BaseTextarea
                  :disabled="editModel == 0 || resolveInfo"
                  placeholder="请输入处理信息"
                  :maxLength="3000"
                  v-model="form.handleDetails"
                  :autoSize="{ minRows: 16, maxRows: 32 }"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 页脚操作栏 -->
          <div class="page-btn-right-top">
            <a-button
              v-if="resolveInfo"
              @click="$close"
            >
              关闭
            </a-button>
            <template v-else>
              <a-button
                type="primary"
                class="button_right"
                @click="handlePreViewWord"
              >预览</a-button>
              <a-button
                type="primary"
                class="ml20"
                @click="handleSubmit"
              >确认签名</a-button>
            </template>
          </div>
        </a-card>
        <!-- 基础信息 -->
        <a-card
          :bordered="false"
          style="margin-bottom: 50px"
        >
          <div
            class="mb20"
            style="font-size: 30px; font-weight: bolder"
          >业务详情</div>
          <title-name title="基础信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            editModel="V"
          ></custom-form>
          <title-name title="质量责任书信息"></title-name>
          <custom-form
            :formList="bookForm"
            :form="book"
            editModel="V"
          ></custom-form>
          <title-name title="申报要求相关附件"></title-name>
          <a-table
            rowKey="id"
            :dataSource="contents"
            :columns="columns"
            :pagination="false"
          >
            <!-- 责任书标题 -->
            <template
              slot="details"
              slot-scope="text, record"
            >
              <div
                v-for="item in record.details"
                :key="item.id"
              >{{ item.content }}</div>
              <!-- <div v-for="item in record.details" :key="item.id">{{ item.serialNumber }}、{{ item.content }}</div> -->
            </template>
          </a-table>
        </a-card>
      </a-spin>
    </a-form-model>
    <!-- 图片预览 -->
    <pre-view
      :preview-image="previewImage"
      :visible.sync="previewVisible"
    />
    <!-- 责任书预览 -->
    <DutyPreView
      ref="dutyPreView"
      :id="book.id"
    />
  </base-breadcrumb>
</template>

<script>
import { duty } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { getSignInfoByUser, addSignInfo, updateSignInfo } from '@/api/system/menuAndAuth.js'
import PreView from '@/components/PreView' // 图片预览
import DutyPreView from './components/DutyPreView' // 责任书预览
import { finishBusinessTodo } from '@/api/commons.js'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    PreView,
    DutyPreView
  },
  data() {
    return {
      loading: false, // 详情加载loading
      editModel: 1, // 0 查看；1 编辑；2 新增
      form: {
        creatorName: void 0,
        createTime: void 0,
        employees: []
      },
      formInfo: {
        imgBase64: ''
      }, // 处理表单
      book: {}, // 责任书表单
      contents: [], // 质量责任书列表
      fileList: [], //文件列表
      previewVisible: false, // 预览控件
      previewImage: '', // 预览图
      iframeContent: '', // 预览责任书内容
      rules: {
        // handleDetails: [{ required: true, whitespace: true, message: '请输入处理信息', trigger: 'change' }]
      } // 表单校验规则
    }
  },
  mounted() {
    this.getSignInfoByUserReq()
    this.loading = true
    duty
      .detailInfo({ id: this.id })
      .then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.form = res.data
          this.book = res.data?.employee?.book ?? {}
          this.contents = res.data?.employee?.book?.contents || []
        }
      })
      .catch(() => {
        this.loading = false
      })
  },
  computed: {
    // 是否是业务待办查看处理信息
    resolveInfo: {
      get() {
        return this.$route.query?.resolveInfo === 'true'
      },
      set() {}
    },
    columns() {
      return [
        {
          dataIndex: 'title',
          title: '责任书标题',
          width: 300
        },
        {
          dataIndex: 'details',
          title: '责任书内容',
          scopedSlots: { customRender: 'details' }
        }
      ]
    },
    // 表单配置项
    formList() {
      return [
        {
          keyName: 'branchComId',
          label: '分公司名称',
          viewName: 'branchComName'
        },
        {
          keyName: 'creatorName',
          label: '创建人'
        },
        {
          keyName: 'createTime',
          label: '创建时间'
        }
      ]
    },
    bookForm() {
      return [
        {
          keyName: 'name',
          label: '责任书名称'
        },
        {
          keyName: 'postName',
          label: '岗位名称'
        },
        {
          keyName: 'bookTypeName',
          label: '岗位类型'
        }
      ]
    }
  },
  methods: {
    /**
     * 预览责任书
     */
    handlePreViewWord() {
      this.$refs.dutyPreView?.handlePreViewWord()
    },
    /**
     * 上传之前
     */
    beforeUpload(file) {
      const isLimitSize = file.size / 1024 <= 2000
      if (!isLimitSize) {
        this.$message.warning('传的图片已超过2M，请重新上传！')
        this.$nextTick(() => {
          this.fileList = []
          this.formInfo.imgBase64 = ''
        })
      }
      return false
    },
    /**
     * 图片改变
     */
    handleImageChange(info) {
      this.fileList = info.fileList
      if (this.fileList.length > 0) {
        const file = this.fileList[0].originFileObj
        // 转为base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (ev) => {
          this.formInfo.imgBase64 = ev.target.result
        }
      } else {
        this.formInfo.imgBase64 = ''
      }
    },
    /**
     * 预览图片
     */
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    /**
     * 获取base64
     */
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    },
    /**
     * 获取签字信息
     */
    async getSignInfoByUserReq() {
      const params = {
        userId: this.$userInfo().id
      }
      const res = await getSignInfoByUser(params)
      this.formInfo = res.data || {}
      // 后台返回的base64需要添加头部信息
      if (this.formInfo.imgBase64) {
        this.formInfo.imgBase64 = 'data:image/png;base64,' + this.formInfo.imgBase64
        this.fileList.push({
          uid: '-1',
          name: 'upload.png',
          status: 'done',
          url: this.formInfo.imgBase64
        })
      }
    },
    /**
     * 转译成文件
     */
    dataURLtoFile(dataurl, filename) {
      try {
        let arr = dataurl && dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], filename, { type: mime })
      } catch (e) {
        console.error(e)
        return ''
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          const { imgBase64 } = this.formInfo
          let pwdBase64 = Date.now()
          const formData = new FormData()
          // 如果没有上传文件，就将base64转为文件，发送给服务器
          const file = (this.fileList[0] && this.fileList[0].originFileObj) || (imgBase64 && this.dataURLtoFile(imgBase64, 'upload.png'))
          formData.append('signImg', file)
          if (!pwdBase64 || !file) {
            // 如果两者只传了一个，不允许提交
            this.$message.warning('签字图片必须提交')
            return
          }
          that.$confirm({
            title: '温馨提示',
            content: '确定提交，提交后不可撤回？',
            onOk: async () => {
              const params = {
                params: {
                  userId: this.$userInfo().id,
                  pwd: pwdBase64,
                  id: this.formInfo.id || void 0
                },
                data: formData
              }
              const fn = this.formInfo.id ? updateSignInfo : addSignInfo
              const res = await fn(params)
              this.formInfo = res.data || {}
              // 后台返回的base64需要添加头部信息
              this.formInfo.imgBase64 = 'data:image/png;base64,' + this.formInfo.imgBase64
              return duty
                .confirmSign({
                  handleDetails: this.form.handleDetails,
                  userId: this.$userInfo().id,
                  id: this.form.id,
                  isLeader: this.noticeType === '304'
                })
                .then((res) => {
                  if (res.data.code === 200) {
                    return finishBusinessTodo({
                      id: this.messageId
                    }).then((res) => {
                      if (res.code == '0') {
                        that.$message.success('提交成功！')
                        that.$multiTab.close()
                      }
                    })
                  }
                })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>